import datetime
import hashlib
import hmac
import logging
import time
from random import getrandbits
from urllib import quote

from config import config
from lib.rest import rest

from django.utils import simplejson as json

# -*- coding: UTF-8 -*-
__license__ = "GPL http://www.gnu.org/licenses/gpl.txt"
__author__="xushengs@gmail.com"
__homepage__ = "http://fdream.net"
__date__ ="2010-2-26 17:39:27"
__version = "0.1"

class gtwtools:
    # time description
    @classmethod
    def semantic_time(self, time_str, time_format):
        """
        semantic time:
        use a short phrase to describ the time
        just like: 2 minutes ago, 2 weeks ago, etc...
        """
        ctime = time.strptime(time_str, time_format)
        std = datetime.datetime(ctime[0],ctime[1],ctime[2],ctime[3],ctime[4],ctime[5])
        curtime = datetime.datetime.utcnow()
        delta = curtime - std
        units = ['year', 'month', 'week', 'hour', 'minute']
        nums = [365, 30, 7, 3600, 60]

        phrase = '' 

        for i in range(0, 5):
            unit = units[i]
            if unit == 'hour' or unit == 'minute':
                count = (delta.seconds // nums[i])
            else:
                count = (delta.days // nums[i])
            
            if count > 0:
                phrase = str(count) + ' ' + unit
                if count > 1:
                    phrase += 's'
                break
        
        if phrase == '':
            if delta.seconds == 0 or delta.seconds == 1:
                phrase = 'just a second'
            else:
                phrase = 'less than %s seconds' % (delta.seconds)
            
        return phrase + ' ago'

    # query string 2 dictionary
    @classmethod
    def qs2dict(self, s):
        dict = {}
        for param in s.split('&'):
            (key, value) = param.split('=')
            dict[key] = value
        return dict

    # dictionary to query string
    @classmethod
    def dict2qs(self, dict):
        return '&'.join(['%s=%s' % (key, value) for key, value in dict.iteritems()])

    # dictionary to query string
    @classmethod
    def dict2qscomma(self, dict):
        return ','.join(['%s="%s"' % (key, value) for key, value in dict.iteritems()])
   
    # get auth parameters
    @classmethod
    def get_oauth_params(self, base_url, params = {}, temp_params = {}, token_secret = '', method = 'POST'):
        default_params = {
            'oauth_consumer_key': config.consumer_key,
            'oauth_signature_method': 'HMAC-SHA1',
            'oauth_timestamp': str(int(time.time())),
            'oauth_nonce': hex(getrandbits(64))[2:],
            'oauth_version': '1.0',
            'oauth_callback': quote(config.callback_url, '~')
        }

        params.update(default_params)
        #params['oauth_callback'] = quote(config.callback_url, '~')

        #for k, v in temp_params.items():
        #    temp_params[k] = quote(str(v), '~')
        #    logging.error('key: %s, value: %s' % (k, temp_params[k]))
        
        temp_params.update(params)
        keys = sorted(list(temp_params.keys()))
        encoded = quote('&'.join(['%s=%s' % (key, temp_params[key]) for key in keys]), '~')
        #logging.error('encoded string: %s\n%s' % (encoded, keys))

        base_string = '%s&%s&%s' % (method, quote(base_url, '~'), encoded)
        key = config.consumer_secret + '&' + token_secret

        params['oauth_signature'] = quote(hmac.new(key, base_string, hashlib.sha1).digest().encode('base64')[:-1], '~')

        return params

    # fetch a url and return json object
    @classmethod
    def get_json(self, url, method='GET', body=None, headers={}, allow_truncated=False, follow_redirects=True, deadline=None):
        #try:
        """
        res = {
            'GET': lambda url: rest.get(url, headers=self.headers),
            'POST': lambda url: rest.post(url, body=body, headers=self.headers),
            'PUT': lambda url: rest.put(url, body=body, headers=self.headers),
            'DELETE': lambda url: rest.delete(url, body=body, headers=self.headers),
            'HEAD': lambda url: rest.head(url, body=body, headers=self.headers)
        }[method.upper()](url)
        """
        method = method.upper()
        res = {'content': ''}
        if method == 'GET':
            res = rest.get(url, headers=headers)
        elif method == 'POST':
            res = rest.post(url, body=body, headers=headers)
        elif method == 'PUT':
            res = rest.put(url, body=body, headers=headers)
        elif method == 'DELETE':
            res = rest.delete(url, body=body, headers=headers)
        elif method == 'HEAD':
            res = rest.head(url, body=body, headers=headers)
        #res = rest.get(url, headers=self.headers)
        
        if res.status_code != 200:
            logging.error('Fetch url error.\n%s\n%s\n%s' % (res.status_code, res.headers, url))
            return None
        
        #"""
        try:
            #object = json.loads(response.content, encoding = 'UTF-8')
            return json.loads(res.content)
        except:
            return None
    #end
